package com.samphanie.auiu.fragment.home

import android.os.Bundle
import android.util.SparseArray
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.lifecycle.SavedStateHandle
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.samphanie.auiu.R
import com.samphanie.auiu.common.ui.component.BaseAppBVMFragment
import com.samphanie.auiu.databinding.FragmentHomeBinding
import com.samphanie.auiu.model.TabCategory
import com.samphanie.auiu.ui.tab.bottom.AuiuTabBottomLayout
import com.samphanie.auiu.ui.tab.common.IAuiuTabLayout
import com.samphanie.auiu.ui.tab.top.AuiuTabTopInfo
import com.samphanie.auiu.ui.tab.top.AuiuTabTopLayout

class HomePageFragment : BaseAppBVMFragment<FragmentHomeBinding, HomeViewModel>() {

    private var topTabSelectIndex: Int = 0
    private val DEFAULT_SELECT_INDEX: Int = 0

    private lateinit var viewPager: ViewPager
    private lateinit var topTabLayout: AuiuTabTopLayout

    override fun getLayoutId(): Int {
        return R.layout.fragment_home
    }

    override fun createViewModel(): HomeViewModel {
        val savedState = SavedStateHandle()
        return HomeViewModel(savedState)
    }

    override fun initialize(savedInstanceState: Bundle?) {
        AuiuTabBottomLayout.clipBottomPadding(binding.viewPager)
        // queryTabList()
        viewModel.queryCategoryTabList().observe(viewLifecycleOwner) {
            it?.let {
                updateUI(it)
            }
        }
    }

    private val onTabSelectedListener =
        IAuiuTabLayout.OnTabSelectedListener<AuiuTabTopInfo<*>> { index, prevInfo, nextInfo ->
            //点击之后选中的那个下标
            if (viewPager.currentItem != index) {
                viewPager.setCurrentItem(index, false)
            }
        }

    private fun updateUI(data: List<TabCategory>) {
        if (!isAlive) return

        viewPager = binding.viewPager
        topTabLayout = binding.topTabLayout

        val topTabs = mutableListOf<AuiuTabTopInfo<Int>>()
        data.forEachIndexed { _, tabCategory ->
            val defaultColor = ContextCompat.getColor(requireContext(), R.color.color_333)
            val selectColor = ContextCompat.getColor(requireContext(), R.color.color_dd2)
            val tabTopInfo = AuiuTabTopInfo(tabCategory.name, defaultColor, selectColor)
            topTabs.add(tabTopInfo)
        }

        topTabLayout.inflateInfo(topTabs as List<AuiuTabTopInfo<*>>)
        topTabLayout.defaultSelected(topTabs[DEFAULT_SELECT_INDEX])
        topTabLayout.addTabSelectedChangeListener(onTabSelectedListener)

        if (viewPager.adapter == null) {
            viewPager.adapter = HomePagerAdapter(
                childFragmentManager,
                FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
            )
            viewPager.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
                override fun onPageSelected(position: Int) {
                    // 这个方法被触发有两种可能，第一种切换顶部tab  第二种 手动滑动翻页
                    // 如果是手动滑动翻页
                    if (position != topTabSelectIndex) {
                        //去通知topTabLayout进行切换
                        topTabLayout.defaultSelected(topTabs[position])
                        topTabSelectIndex = position
                    }
                }
            })
        }
        (viewPager.adapter as HomePagerAdapter).update(data)
    }

    inner class HomePagerAdapter(fm: FragmentManager, behavior: Int) :
        FragmentPagerAdapter(fm, behavior) {
        val tabs = mutableListOf<TabCategory>()
        private val fragments = SparseArray<Fragment>(tabs.size)
        override fun getItem(position: Int): Fragment {
            val cateId = tabs[position].id
            val cateIdKey = cateId.toInt()
            var fragment = fragments.get(cateIdKey, null)
            if (fragment == null) {
                fragment = HomeTabFragment.newInstance(tabs[position].id)
                fragments.put(cateIdKey, fragment)
            }
            return fragment
        }

        override fun getCount(): Int {
            return tabs.size
        }

        override fun getItemPosition(`object`: Any): Int {
            val indexOfValue = fragments.indexOfValue(`object` as Fragment)
            val fragment = getItem(indexOfValue)
            return if (fragment == `object`) PagerAdapter.POSITION_UNCHANGED else PagerAdapter.POSITION_NONE
        }

        override fun getItemId(position: Int): Long {
            return tabs[position].id.toLong()
        }

        fun update(list: List<TabCategory>) {
            tabs.clear()
            tabs.addAll(list)
            notifyDataSetChanged()
        }
    }

}